﻿using Microsoft.AspNetCore.Mvc;
using PCH.Models;
using PCH.Services;
using System.Diagnostics;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using PCH.Services.Dto;
using OfficeOpenXml;
using OfficeOpenXml.Style;
using System.IO;
using System.IO.Pipes;
using System.Text;
using Microsoft.EntityFrameworkCore.Metadata;

namespace PCH.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private readonly ICommonService _commonService;
        private readonly IAuditService _auditService;

        public HomeController(ILogger<HomeController> logger,
                              ICommonService commonService,
                              IAuditService auditService)
        {
            _logger = logger;
            _commonService = commonService;
            _auditService = auditService;
        }

        public IActionResult Index()
        {
            return View();
        }

        [HttpGet]
        [Route("api/home/get-home-view")]
        public async Task<IActionResult> GetHomeView()
        {
            AmisRes amisRes = _commonService.GetAmisRes();
            string schema =await _commonService.GetResourceStringAsync("AmisSchema.home-view.json");
            _logger.LogInformation(schema);
            if (!string.IsNullOrEmpty(schema))
            {
                amisRes.Data = new { amisJson=schema};
            }
            return  Json(amisRes);
        }

        [HttpGet]
        [Route("api/home/get-cards-data")]
        public IActionResult GetCardsData(DateTime startTime,DateTime endTime)
        {
            AmisRes amisRes = _commonService.GetAmisRes();
            if (startTime.Year == 1)
            {
                startTime = DateTime.Now.Date;
                endTime = DateTime.Now.AddDays(1).Date;
            }
            var items = _auditService.GetCardData(startTime,endTime);
            amisRes.Data = new { items = items };
            return Json(amisRes);
        }

        [HttpGet]
        [Route("api/home/get-table-data")]
        public IActionResult GetTableData()
        {
                var query = Request.Query;
                var startTime = Convert.ToDateTime(query["startDate"]).Date;
                var endTime = Convert.ToDateTime(query["endTime"]).AddDays(1).Date;
                if (startTime.Year == 1)
                {
                    startTime = DateTime.Now.Date;
                    endTime = DateTime.Now.Date.AddDays(1);
                }
                int page = Convert.ToInt32(query["page"]);
                int perPage = Convert.ToInt32(query["perPage"]);
                int totalCount = 0;
                var list = _auditService.GetTableData(startTime, endTime, page, perPage,out totalCount); 
                AmisRes res = _commonService.GetAmisRes();
                res.Status = 0;
               
                res.Data = new
                {
                    items = list,
                    count = totalCount
                };
                HttpContext.Session.SetString("data", JsonConvert.SerializeObject(list));
                return Json(res);
        }

        [HttpGet("api/home/downDataExcel1")]
        public IActionResult ExportAndDownloadExcel()
        {
            try
            {
                var dataStr = HttpContext.Session.GetString("data")!;
                if (!string.IsNullOrEmpty(dataStr))
                {
                    List<AuditViewModel>? list = JsonConvert.DeserializeObject<List<AuditViewModel>>(dataStr);
                    if (list != null)
                    {
                        List<string[]> dataList = list.Select(p => new string[]
                        {
                        p.AuditDate,
                        p.RegistCount.ToString(),
                        p.CompletedCount.ToString(),
                        p.UnDoCount.ToString(),
                        p.CompletedPec.ToString(),
                        p.UnDoRate.ToString()
                        }).ToList<string[]>();
                        // 新内存流
                        ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
                        using (var package = new ExcelPackage())
                        {
                            var workSheet = package.Workbook.Worksheets.Add("超声科工作统计");
                            string[] heads = new string[] { "日期", "登记量", "完成量", "未完成量", "完成率", "未完成率" };
                            dataList.Insert(0, heads);
                            for (int i = 0; i < dataList.Count; i++)
                            {
                                for (int j = 0; j < dataList[i].Length; j++)
                                {
                                    workSheet.Cells[i + 1, j + 1].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
                                    workSheet.Cells[i + 1, j + 1].Value = dataList[i][j];
                                }
                            }
                            var stream = new MemoryStream(package.GetAsByteArray());
                            stream.Position = 0;
                            string filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "WorkLoadAudit.xlsx");
                            using (var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
                            {
                                stream.CopyTo(fileStream);
                                stream.Flush();
                                fileStream.Flush();
                            }

                            // 设置响应头
                            Response.Headers.Add("Content-Disposition", "attachment; filename=example.xlsx");
                            // 返回文件
                            //return PhysicalFile(filePath, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "example.xlsx");
                            var file = System.IO.File.Open("WorkLoadAudit.xlsx", FileMode.Open, FileAccess.ReadWrite);
                            return new FileStreamResult(file, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
                            {
                                FileDownloadName = DateTime.Now.ToString("MMddhhmmss") + ".xlsx"
                            };
                        }
                    }
                }
                return Ok();
            }
            catch (Exception ex)
            {
                return Ok();
            }
        }


        //[HttpGet("api/home/downDataExcel")]
        //public IActionResult DownXlsx()
        //{
        //    string filePath = Path.Combine(Directory.GetCurrentDirectory(),"wwwroot", "WorkLoadAudit.xlsx");
        //    if (!System.IO.File.Exists(filePath))
        //    {
        //        return NotFound("未找到文件");
        //    }

        //    //// byte[] bytes = System.IO.File.ReadAllBytes(filePath);
        //    //_logger.LogInformation($"文件路径：{filePath},文件大小：{bytes.Length}字节");
        //    //if (bytes != null && bytes.Length > 0)
        //    //{
        //    //    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        //    //    Response.Headers.Add("Content-Length",bytes.Length.ToString());
        //    //    Response.Headers.Add("Content-Disposition", "attachment; filename=download.xlsx");
        //    //    return File(bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        //    //}
        //    return File("dada.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;","download.xlsx");
        //}



        // 导出到CSV
        [HttpGet("api/home/downDataExcel")]
        public IActionResult DownCSV()
        {
            var dataStr = HttpContext.Session.GetString("data")!;
            if (!string.IsNullOrEmpty(dataStr))
            {
                List<AuditViewModel>? list = JsonConvert.DeserializeObject<List<AuditViewModel>>(dataStr);
                if (list != null)
                {
                    List<string[]> dataList = list.Select(p => new string[]
                    {
                        p.AuditDate,
                        p.RegistCount.ToString(),
                        p.CompletedCount.ToString(),
                        p.UnDoCount.ToString(),
                        p.CompletedPec.ToString(),
                        p.UnDoRate.ToString()
                    }).ToList<string[]>();
                    string filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "WorkLoadAudit.csv");
                    using(var writer = new StreamWriter(filePath, false, Encoding.UTF8))
                    {
                        // 表头
                        string[] heads = new string[] { "日期", "登记量", "完成量", "未完成量", "完成率", "未完成率" };
                        for (int i = 0; i < heads.Length; i++)
                        {
                            writer.Write(heads[i]);
                            if (i < heads.Length - 1)
                            { 
                                writer.Write(',');
                            }
                        };
                        writer.WriteLine();
                        // 写入数据
                        foreach(var row in dataList)
                        {
                            for (int i=0;i<row.Length;i++)
                            {
                                writer.Write(row[i]);
                                if (i < row.Length - 1)
                                {
                                    writer.Write(",");
                                }
                            }
                            writer.WriteLine();
                        }
                    }
                    return File("/WorkLoadAudit.csv", "text/csv","down.csv");
                }
            }
            return Ok();
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}
